﻿using Dapper;
using Furion;
using Gear.Application.Appsettings;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Gear.Web.Core
{
    [AppStartup(600)]
    public class WebCoreStartup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews()
            .AddAppLocalization();  // 注册多语言
            services.AddCorsAccessor();

            services.AddJwt();

            services.AddControllers()
                    .AddInjectWithUnifyResult();

            services.AddControllers()
                    .AddDynamicApiControllers();

            services.AddControllers()
                    .AddFriendlyException();

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddMemoryCache();


            services.AddConfigurableOptions<AppInfoOptions>();
          
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            // 配置多语言，必须在 路由注册之前
            app.UseAppLocalization();

            // 路由中间件
            app.UseRouting();

            // 跨域中间件
            app.UseCorsAccessor(builder =>
                builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
            );

            // 鉴权中间件
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto });

            // 指定当前服务stream name
            // 如果 app.UseInject() 不输入参数，则默认地址为 /api，如果输入 string.Empty 则为 / 目录。如果输入任意字符串，则为 /任意字符串 目录。
            app.UseInject("service");
        }
    }
}